package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.system.domain.Investigation;
import com.ruoyi.system.domain.InvestigationUserAnswer;
import com.ruoyi.system.domain.bo.InvestigationUserAnswerBo;
import com.ruoyi.system.domain.vo.InvestigationUserAnswerVo;
import com.ruoyi.system.enums.PubStatusEnum;
import com.ruoyi.system.mapper.InvestigationMapper;
import com.ruoyi.system.mapper.InvestigationUserAnswerMapper;
import com.ruoyi.system.service.IInvestigationUserAnswerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户问卷答案Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-13
 */
@RequiredArgsConstructor
@Service
public class InvestigationUserAnswerServiceImpl implements IInvestigationUserAnswerService {

    private final InvestigationUserAnswerMapper baseMapper;

    private final InvestigationMapper investigationMapper;

    /**
     * 新增用户问卷答案
     */
    @Override
    public Boolean insertByBos(Long investigationId, Long userId, List<InvestigationUserAnswerBo> bos) {

        Investigation investigation = investigationMapper.selectById(investigationId);
        if (investigation == null || !PubStatusEnum.PUBLISHED.getValue().equals(investigation.getPubStatus())) {
            throw new UnsupportedOperationException("问卷不存在");
        }

        List<InvestigationUserAnswerVo> answers = baseMapper.getByInvestigationIdAndUserId(investigationId, userId);
        if (!CollectionUtils.isEmpty(answers)) {
            throw new UnsupportedOperationException("已回答过该问卷");
        }
        List<InvestigationUserAnswer> adds = BeanUtil.copyToList(bos, InvestigationUserAnswer.class);
        for (InvestigationUserAnswer add : adds) {
            add.setInvestigationId(investigationId);
            add.setUserId(userId);
        }
        validEntityBeforeSave(adds);
        return baseMapper.insertBatch(adds);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(List<InvestigationUserAnswer> answers) {
        //TODO 做一些数据校验,如唯一约束
    }
}
